package com.jwdf.uda.view.tag;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jwdf.uda.R;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.CheckableView;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/13.
 */
public class StyleTagView extends RelativeLayout {

    private List<Tag> mTags = new ArrayList<>();
    private int mTag=10;
    private List<Checkable> checkableList=new ArrayList<>();

    private LayoutInflater mInflater;
    private ViewTreeObserver mViewTreeObserber;

    private OnTagClickListener mClickListener;
    private OnTagDeleteListener mDeleteListener;

    private int mWidth;

    private boolean mInitialized = false;

    private int lineMargin;
    private int tagMargin;
    private int textPaddingLeft;
    private int textPaddingRight;
    private int textPaddingTop;
    private int texPaddingBottom;

    public StyleTagView(Context ctx) {
        super(ctx, null);
        initialize(ctx, null, 0);
    }

    public StyleTagView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        initialize(ctx, attrs, 0);
    }

    public StyleTagView(Context ctx, AttributeSet attrs, int defStyle) {
        super(ctx, attrs, defStyle);
        initialize(ctx, attrs, defStyle);
    }

    private void initialize(Context ctx, AttributeSet attrs, int defStyle) {
        mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mViewTreeObserber = getViewTreeObserver();
        mViewTreeObserber.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!mInitialized) {
                    mInitialized = true;
                    drawTags();
                }
            }
        });
        final CheckableView tagLayout = (CheckableView)mInflater.inflate(R.layout.view_style_tag, null);
        int a=tagLayout.getWidth();
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        // get AttributeSet
        TypedArray typeArray = ctx.obtainStyledAttributes(attrs, R.styleable.TagView, defStyle, defStyle);
        this.lineMargin = (int) typeArray.getDimension(R.styleable.TagView_lineMargin, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_LINE_MARGIN));
        this.tagMargin = (int) typeArray.getDimension(R.styleable.TagView_tagMargin, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_TAG_MARGIN));
        this.textPaddingLeft = (int) typeArray.getDimension(R.styleable.TagView_textPaddingLeft, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_TAG_TEXT_PADDING_LEFT));
        this.textPaddingRight = (int) typeArray.getDimension(R.styleable.TagView_textPaddingRight, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_TAG_TEXT_PADDING_RIGHT));
        this.textPaddingTop = (int) typeArray.getDimension(R.styleable.TagView_textPaddingTop, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_TAG_TEXT_PADDING_TOP));
        this.texPaddingBottom = (int) typeArray.getDimension(R.styleable.TagView_textPaddingBottom, UdaUtils.convertDipToPx(this.getContext(), Constants.DEFAULT_TAG_TEXT_PADDING_BOTTOM));
        typeArray.recycle();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        if (width <= 0)
            return;
        mWidth = getMeasuredWidth();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTags();
    }

    private void drawTags() {
        if (!mInitialized) {
            return;
        }
        // clear all tag
        removeAllViews();
        // layout padding left & layout padding right
        float total = getPaddingLeft() + getPaddingRight();
        int listIndex = 1;// List Index
        int indexBottom = 1;// The Tag to add below
        int indexHeader = 1;// The header tag of this line
        Tag tagPre = null;
        checkableList.clear();
        for (Tag item : mTags) {
            final int position = listIndex - 1;
            final Tag tag = item;

            // inflate tag layout
            final CheckableView tagLayout = (CheckableView)mInflater.inflate(R.layout.view_style_tag, null);
            tagLayout.setId(listIndex);
            tagLayout.setBackgroundDrawable(getSelector(tag));

            // tag text
            final CheckedTextView tagView = (CheckedTextView) tagLayout.findViewById(R.id.tv_tag_item_contain);
            String source = tag.text;
            int length = source.length();
            if (length > 7) {
                source = source.substring(0, 7) + "...";
                tagView.setText(source);
            } else {
                tagView.setText(source);
            }
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tagView.getLayoutParams();
            params.setMargins(textPaddingLeft, textPaddingTop, textPaddingRight, texPaddingBottom);
            tagView.setLayoutParams(params);
            tagView.setTextSize(TypedValue.COMPLEX_UNIT_SP, tag.tagTextSize);
            Checkable checkable=new Checkable();
            checkable.setTagLayout(tagLayout);
            checkable.setTagView(tagView);
            checkableList.add(checkable);
            tagLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    tagLayout.toggle();
                    tagLayout.setChecked(tagLayout.isChecked());
                    tagView.toggle();
                    tagView.setChecked(tagView.isChecked());
                    if (mClickListener != null&& tagLayout.isChecked()) {
                        mClickListener.onTagClick(tag, position);
                        setOnTagSelected(position,tagLayout,tagView);
                    }
                }
            });
            // calculate　of tag layout width
            float tagWidth = tagView.getPaint().measureText(tag.text) + textPaddingLeft + textPaddingRight;
            // tagView padding (left & right)
            // deletable text
            TextView deletableView = (TextView) tagLayout.findViewById(R.id.tv_tag_item_delete);
            if (tag.isDeletable) {
                deletableView.setVisibility(View.VISIBLE);
                deletableView.setText(tag.deleteIcon);
                int offset = UdaUtils.convertDipToPx(getContext(), 2f);
                deletableView.setPadding(offset, textPaddingTop, textPaddingRight + offset, texPaddingBottom);
                deletableView.setTextColor(tag.deleteIndicatorColor);
                deletableView.setTextSize(TypedValue.COMPLEX_UNIT_SP, tag.deleteIndicatorSize);
                deletableView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mDeleteListener != null) {
                            Tag targetTag = tag;
                            mDeleteListener.onTagDeleted(StyleTagView.this, targetTag, position);
                        }
                    }
                });
                tagWidth += deletableView.getPaint().measureText(tag.deleteIcon) + textPaddingLeft + textPaddingRight;
                // deletableView Padding (left & right)
            } else {
                deletableView.setVisibility(View.GONE);
            }
            LayoutParams tagParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            //add margin of each line
            tagParams.bottomMargin = lineMargin;
            if (mWidth <= total + tagWidth + UdaUtils.convertDipToPx(this.getContext(), Constants.LAYOUT_WIDTH_OFFSET)) {
                //need to add in new line
                tagParams.addRule(RelativeLayout.BELOW, indexBottom);
                // initialize total param (layout padding left & layout padding right)
                total = getPaddingLeft() + getPaddingRight();
                indexBottom = listIndex;
                indexHeader = listIndex;
            } else {
                //no need to new line
                tagParams.addRule(RelativeLayout.ALIGN_TOP, indexHeader);
                //not header of the line
                if (listIndex != indexHeader) {
                    tagParams.addRule(RelativeLayout.RIGHT_OF, listIndex - 1);
                    float totalTagWidth=tagWidth*mTags.size();
                    float margin=mWidth-totalTagWidth;
                    tagMargin=(int)margin/(mTags.size()-1);
                    tagParams.leftMargin = tagMargin;
                    total += tagMargin;
                    if (tagPre != null && tagPre.tagTextSize < tag.tagTextSize) {
                        indexBottom = listIndex;
                    }
                }
            }
            total += tagWidth;
            addView(tagLayout, tagParams);
            tagPre = tag;
            listIndex++;
        }
    }

    private Drawable getSelector(Tag tag) {
        if (tag.background != null) return tag.background;
        StateListDrawable states = new StateListDrawable();
        GradientDrawable gdNormal = new GradientDrawable();
        gdNormal.setColor(tag.layoutColor);
        gdNormal.setCornerRadius(tag.radius);
        if (tag.layoutBorderSize > 0) {
            gdNormal.setStroke(UdaUtils.convertDipToPx(getContext(), tag.layoutBorderSize), tag.layoutBorderColor);
        }
        GradientDrawable gdPress = new GradientDrawable();
        gdPress.setColor(tag.layoutColorPress);
        gdPress.setCornerRadius(tag.radius);
        states.addState(new int[]{android.R.attr.state_checked}, gdPress);
        //must add state_pressed first，or state_pressed will not take effect
        states.addState(new int[]{}, gdNormal);
        return states;
    }

    public void addTag(Tag tag) {
        mTags.add(0, tag);
        drawTags();
    }

    public void addTags(List<Tag> tags) {
        if (tags == null) return;
        mTags = new ArrayList<>();
        if (tags.isEmpty())
            drawTags();
        for (Tag item : tags) {
            addTag(item);
        }
    }

    public void addTags(String[] tags) {
        if (tags == null) return;
        for (String item : tags) {
            Tag tag = new Tag(item);
            addTag(tag);
        }
    }

    /*public void addTags(ArrayList<String> tags){
        if (tags==null)return;
		for(String item:tags){
			Tag tag = new Tag(item);
			addTag(tag);
		}
	}*/

    public List<Tag> getTags() {
        return mTags;
    }

    public void remove(int position) {
        if (position < mTags.size()) {
            mTags.remove(position);
            drawTags();
        }
    }

    public void removeAll() {
        removeAllViews();
    }

    public int getLineMargin() {
        return lineMargin;
    }

    public void setLineMargin(float lineMargin) {
        this.lineMargin = UdaUtils.convertDipToPx(getContext(), lineMargin);
    }

    public int getTagMargin() {
        return tagMargin;
    }

    public void setTagMargin(float tagMargin) {
        this.tagMargin = UdaUtils.convertDipToPx(getContext(), tagMargin);
    }

    public int getTextPaddingLeft() {
        return textPaddingLeft;
    }

    public void setTextPaddingLeft(float textPaddingLeft) {
        this.textPaddingLeft = UdaUtils.convertDipToPx(getContext(), textPaddingLeft);
    }

    public int getTextPaddingRight() {
        return textPaddingRight;
    }

    public void setTextPaddingRight(float textPaddingRight) {
        this.textPaddingRight = UdaUtils.convertDipToPx(getContext(), textPaddingRight);
    }

    public int getTextPaddingTop() {
        return textPaddingTop;
    }

    public void setTextPaddingTop(float textPaddingTop) {
        this.textPaddingTop = UdaUtils.convertDipToPx(getContext(), textPaddingTop);
    }

    public int getTexPaddingBottom() {
        return texPaddingBottom;
    }

    public void setTexPaddingBottom(float texPaddingBottom) {
        this.texPaddingBottom = UdaUtils.convertDipToPx(getContext(), texPaddingBottom);
    }

    public void setOnTagClickListener(OnTagClickListener clickListener) {
        mClickListener = clickListener;
    }

    public void setOnTagDeleteListener(OnTagDeleteListener deleteListener) {
        mDeleteListener = deleteListener;
    }

    public void setOnTagSelected(int position, CheckableView tagLayout, CheckedTextView tagView){
        for(int i=0;i<mTags.size();i++){
            if(i==position){
            }else {
                if(checkableList.get(i).getTagLayout().isChecked()) {
                    checkableList.get(i).getTagLayout().toggle();
                    checkableList.get(i).getTagLayout().setChecked(checkableList.get(i).getTagLayout().isChecked());
                    checkableList.get(i).getTagView().toggle();
                    checkableList.get(i).getTagView().setChecked(checkableList.get(i).getTagView().isChecked());
                }
            }
        }
    }

    public void setOnTagClick(int i){
        try {
            checkableList.get(i).getTagLayout().toggle();
            checkableList.get(i).getTagLayout().setChecked(checkableList.get(i).getTagLayout().isChecked());
            checkableList.get(i).getTagView().toggle();
            checkableList.get(i).getTagView().setChecked(checkableList.get(i).getTagView().isChecked());
        }catch (Exception e){

        }

    }

    public int setOnTagSelected(){
        mTag=10;
        for(int i=0;i<mTags.size();i++){
                if(checkableList.get(i).getTagLayout().isChecked()) {
                    mTag=i;
                }
        }
        return mTag;
    }

    public void setSize(){}
}
